package tech.aichan.AiQA.handler;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import tech.aichan.AiQA.common.BaseResponse;
import tech.aichan.AiQA.model.entity.login.LoginUser;
import tech.aichan.AiQA.utils.WebUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

/**
 * @author mengyu
 * 认证异常处理器 (AuthenticationException)
 * @date 2024/03/03 9:42
 */
@Component
@Slf4j
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(!Objects.isNull(authentication)){
            LoginUser user = (LoginUser) authentication.getPrincipal();
            log.info("auth failed: {}",user.getUser().getId());
        }
        // 包装Response对象并写入HttpServletResponse
        BaseResponse<String> result = BaseResponse.error(HttpStatus.HTTP_NOT_AUTHORITATIVE,"登录错误:"+authException.getMessage());
        String json = JSON.toJSONString(result);
        WebUtils.renderString(response,json);
    }
}
